package com.huangyong.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.huangyong.entity.Article;
import com.huangyong.entity.Comment;
import com.huangyong.entity.User;
import com.huangyong.service.ArticleService;
import com.huangyong.service.CommentService;
import com.huangyong.service.UserService;

@Controller
public class WebBeforeController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private CommentService commentService;
	
	@RequestMapping("/")
	public String WebBeforeIndex(HttpSession session) {
		List<Article> articles = articleService.findAll();
		session.setAttribute("articles", articles);
		return "/foreground/index";
	}

	@RequestMapping(value="/articleDetail/{aid}")
	public String ArticleDetail(@PathVariable("aid") int aid,HttpSession session) {
		Article article = articleService.findById(aid);
		session.setAttribute("article", article);
		
		List<Comment> comments = commentService.findAll(aid);
		session.setAttribute("comments", comments);
		return "/foreground/detail";
	}
	
	@RequestMapping(value="/toAddArticle")
	public String ToAddArticle() {
		return "/foreground/add";
	}
	
	@RequestMapping(value="/addArticle")
	public String AddArticle(HttpSession session,String title,String author,String content,int readcount) {
		User user = userService.findByUsername(author);
		Article article = new Article(title,user,content,readcount);
		String result = articleService.insert(article);
		if(result.equals("success")) {
			session.setAttribute("addArticlemsg", "添加文章成功！");
		}else {
			session.setAttribute("addArticlemsg", "添加文章失败！");
		}
		return ToAddArticle();
	}
	
	@RequestMapping(value="/addCommentByArticle/{aid}")
	public String AddCommentByArticle(@PathVariable("aid") int aid,String author,String content,HttpSession session) {
		User user = userService.findByUsername(author);
		Comment comment = new Comment(aid,user,content);
		String result = commentService.insert(comment);
		if(result.equals("success")) {
			session.setAttribute("addcommentmsg", "添加评论成功");
		}else {
			session.setAttribute("addcommentmsg", "添加评论成功");
		}
		return ArticleDetail(aid,session);
	}
}
